package ce.com.cenewbluesdk.proxy;


import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;

import ce.com.cenewbluesdk.CEBC;
import ce.com.cenewbluesdk.bluetooth.CEBlueTooth_3;
import ce.com.cenewbluesdk.connect.ReconnectModeA;
import ce.com.cenewbluesdk.entity.CEDevData;
import ce.com.cenewbluesdk.entity.k2.K2_CESyncTime;
import ce.com.cenewbluesdk.entity.k3.Battery_Info_Struct_K3;
import ce.com.cenewbluesdk.entity.k3.Dev_Info_Struct_K3;
import ce.com.cenewbluesdk.entity.k3.Dev_NFC_Info;
import ce.com.cenewbluesdk.entity.k3.Message_notice_struct_K3;
import ce.com.cenewbluesdk.entity.k3.Mix_Info_Struct_K3;
import ce.com.cenewbluesdk.entity.k3.Mix_sport_Struct;
import ce.com.cenewbluesdk.entity.k3.OTAStateInfo;
import ce.com.cenewbluesdk.entity.k3.Send_Alarm_Info_Struct_K3;
import ce.com.cenewbluesdk.entity.k3.Send_Bt_NeedPair_T_K3;
import ce.com.cenewbluesdk.entity.k3.Send_Dev_Setting_Struct_K3;
import ce.com.cenewbluesdk.entity.k3.Send_Goal;
import ce.com.cenewbluesdk.entity.k3.Send_Time_Sync_Struct_K3;
import ce.com.cenewbluesdk.entity.k3.Send_User_Card;
import ce.com.cenewbluesdk.entity.k3.Send_User_Info_Struct_K3;
import ce.com.cenewbluesdk.entity.k3.Send_Watch_Face_And_Notification_Set_K3;
import ce.com.cenewbluesdk.entity.k3.Send_Weather_Struct_K3;
import ce.com.cenewbluesdk.entity.k3.Send_contacts;
import ce.com.cenewbluesdk.entity.k3.Send_note;
import ce.com.cenewbluesdk.entity.k3.Sport_Info_Struct_K3;
import ce.com.cenewbluesdk.queue.CEProtocolA;
import ce.com.cenewbluesdk.uitl.ByteParser;
import ce.com.cenewbluesdk.uitl.ByteUtil;
import ce.com.cenewbluesdk.uitl.Lg;


/**
 * Created by Administrator on 2016/11/9 0009.
 */
public class CEDevK3Proxy extends CEBluetoothProxyBase {

    public static final int devType = 4;

    SendHelper sendHelper = new SendHelper();

    protected CEDevK3Proxy(Context context) {
        super(context);
    }

    public SendHelper getSendHelper() {
        return sendHelper;
    }


    public boolean sendPmessage(Message msg) {
        sendMeg(msg);
        return true;
    }

    public boolean sendPmessage(int what, Object obj) {
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        sendMeg(msg);
        return true;
    }

    @Override
    protected void dataSendSucceed(CEDevData devData) {
        if (devData.getDataType() == CEBC.K3.DATA_TYPE_TIME) {
            Lg.e("时间发送成功");
        }
    }

    @Override
    protected void DataSendFailed(CEDevData devData) {
    }

    @Override
    protected void receiptData(CEDevData devData) {
        Lg.e("收到一个整的数据包:" + devData.toString());
        handleRcvdBlock(devData);


    }

    @Override
    protected void blueToothConnectStateChange(int state) {

        Lg.e("liu 连接状态改变 " + state);
        sendMeg(createMessage(CEBC.BLUE_CONNECT_STATE_CHANGE, state));

    }

    @Override
    protected void initProxy() {
        blueTooth = new CEBlueTooth_3(context);
        connectUtil = new CEConnectUtil(context, new ReconnectModeA(), this, blueTooth);
        devQueue = new CEDevQueue(this, new CEProtocolA(devType), blueTooth);
    }

    @Override
    protected String getClassName() {
        return "CEDevK3Proxy";
    }




    public class SendHelper {
        public void sendTime() {
            Send_Time_Sync_Struct_K3 time = Send_Time_Sync_Struct_K3.getCurrentTime_K3();
            devQueue.push(time.toCEDevData());
        }


        /**
         * 发送用户信息
         */
        public void sendUserInfo(int userid, int gender, int age, int height, int weight, int lr_hand) {
            try {
                Send_User_Info_Struct_K3 user_Info_Struct = new Send_User_Info_Struct_K3(userid,
                        (byte) gender, (byte) age, (byte) height, (byte) weight, (byte) (lr_hand));
                devQueue.push(user_Info_Struct.toCEDevData());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * 发送用户信息
         */
        public void sendUserInfo(Send_User_Info_Struct_K3 user_Info_Struct, int userid) {
            try {
                user_Info_Struct.setUserid(userid);
                devQueue.push(user_Info_Struct.toCEDevData());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        /**
         * 短信通知信息
         */
        public void sendMessage_notice(
                long time, String name, String content, byte messageType) {
            if (name == null || content == null) {
                return;
            }
            Log.e("liu", "短信发送给设备侧了  。");
            Message_notice_struct_K3 msg = new Message_notice_struct_K3(time, messageType);
            msg.setSendContext(name, Message_notice_struct_K3.Property.TYPE_CONTENT, content);

            sendMessage_notice(msg);
        }

        public void sendMessage_notice(Message_notice_struct_K3 msg) {
            devQueue.push(msg.toCEDevData());
        }

        /**
         * 发送闹钟设置信息
         */
        public void sendAlarmInfo(
                ArrayList<Send_Alarm_Info_Struct_K3> alarm_Info_Structs) {
//            if (alarm_Info_Structs == null || alarm_Info_Structs.size() == 0)
//                return;
            byte[] payload = new byte[Send_Alarm_Info_Struct_K3.getItemSize() * alarm_Info_Structs.size() + 1];
            Lg.e("发送闹钟设置信息,共" + alarm_Info_Structs.size() + "组闹钟");
            payload[0] = (byte) alarm_Info_Structs.size();
            for (int i = 0; i < alarm_Info_Structs.size(); ++i) {
                Send_Alarm_Info_Struct_K3 this_alrm = alarm_Info_Structs.get(i);
                byte[] this_alarm_payload = this_alrm.getBytes();
                System.arraycopy(this_alarm_payload, 0, payload, i * Send_Alarm_Info_Struct_K3.getItemSize() + 1, Send_Alarm_Info_Struct_K3.getItemSize());
            }
            Lg.e("发送闹钟设置信息,payload : " + Arrays.toString(payload));
            CEDevData data = new CEDevData();
            data.setCmd(CEBC.CMD_SEND_TYPE);
            data.setDataType(CEBC.K3.DATA_TYPE_ALARM);
            data.setItemL(payload.length);
            data.setData(payload);
            data.setItemNumber(1);
            devQueue.push(data);

        }

        /**
         * 来电通知信息
         */
        public void sendCall_notice(long time, String name, String num) {
            Message_notice_struct_K3 msg = new Message_notice_struct_K3(time, Message_notice_struct_K3.TYPE_PHONE);
//            msg.addProperty(Message_notice_struct_K3.Property.TYPE_NAME, name);
//            msg.addProperty(Message_notice_struct_K3.Property.TYPE_PHONE_NUM, num);
            msg.setSendContext(name, Message_notice_struct_K3.Property.TYPE_PHONE_NUM, num);
            devQueue.push(msg.toCEDevData());


        }


        /**
         * 发送混杂数据
         *
         * @param mixinfo
         */
        public void sendMixInfo(Mix_Info_Struct_K3 mixinfo) {
            byte[] payload = mixinfo.getBytes();
            CEDevData data = new CEDevData();
            data.setCmd(CEBC.CMD_SEND_TYPE);
            data.setDataType(CEBC.K3.DATA_TYPE_DEV_SYNC);
            data.setItemL(payload.length);
            data.setItemNumber(1);
            data.setData(payload);
            devQueue.push(mixinfo.toCEDevData());
        }

        /**
         * 获取混杂数据
         */
        public void getMixInfo() {
            CEDevData data = new CEDevData();
            data.setCmd(CEBC.CMD_REQUEST_TYPE);
            data.setDataType(CEBC.K3.DATA_TYPE_DEV_SYNC);

            devQueue.push(data);
        }

        /**
         * 发送天气信息
         *
         * @param mSend_Weather_Struct_K3
         */
        public void sendWeatherInfo(Send_Weather_Struct_K3 mSend_Weather_Struct_K3) {
            devQueue.push(mSend_Weather_Struct_K3.toCEDevData());
        }

        /**
         * 发送设备配置信息
         *
         * @param dev_Setting_Struct
         */
        public void sendSetting(Send_Dev_Setting_Struct_K3 dev_Setting_Struct) {
            devQueue.push(dev_Setting_Struct.toCEDevData());
        }

        /**
         * 发送正常重连上以后的配对密码
         *
         * @param pwd
         */
        public void sendReconnectPairPwd(int pwd, int pairType) {
            byte[] result = pwd2bytes4(pwd);
            Send_Bt_NeedPair_T_K3 bt_needpair_t = new Send_Bt_NeedPair_T_K3(Send_Bt_NeedPair_T_K3.PHONE_ANDROID, CEBC.TYPE.PAIR_CONNECT_NOSENDINFO,
                    result, (byte) pairType);
            devQueue.push(bt_needpair_t.toCEDevData());
        }

        /**
         * 发送第一次配对的密码,用于绑定的过程
         *
         * @param pwd
         */
        public void sendFirstPairePwd(int pwd, int pairType) {
            byte[] result = pwd2bytes4(pwd);
            Send_Bt_NeedPair_T_K3 bt_needpair_t = new Send_Bt_NeedPair_T_K3(Send_Bt_NeedPair_T_K3.PHONE_ANDROID, CEBC.TYPE.PAIR_CONNECT_LOCAL,
                    result, (byte) pairType);
            devQueue.push(bt_needpair_t.toCEDevData());
        }

        private byte[] pwd2bytes4(int pwd) {
            byte[] bytes = new byte[4];
            bytes[0] = (byte) (pwd / 1000 + '0');
            bytes[1] = (byte) (pwd % 1000 / 100 + '0');
            bytes[2] = (byte) (pwd % 100 / 10 + '0');
            bytes[3] = (byte) (pwd % 10 + '0');
            return bytes;
        }

        /**
         * 设置gesensor数据传输开关
         */
        public void setEnableGsDataTrans(boolean enable) {
            CEDevData data = new CEDevData(CEBC.CMD_SEND_TYPE, CEBC.K3.DATA_TYPE_SET_GSEND);
            data.setOtherData(new byte[]{(byte) (enable ? 1 : 0)});
            devQueue.push(data);
        }

        /**
         * 发送配对成功
         */
        public void sendPairFinish() {
            CEDevData data = new CEDevData(CEBC.CMD_SEND_TYPE, CEBC.K3.DATA_TYPE_PAIR_FINISH);
            devQueue.push(data);
        }

        /**
         * 获取设备信息
         */
        public void getDevInfo() {
            CEDevData data = new CEDevData(CEBC.CMD_REQUEST_TYPE, CEBC.K3.DATA_TYPE_DEVINFO);
            devQueue.push(data);
        }

        /**
         * 发送联系人
         */
        public void sendPhoneBook(ArrayList<Send_contacts> contactses, int index) {
            if (index >= contactses.size()) {
                return;
            }
            byte[] date;
            if (index + 6 < contactses.size()) {
                date = new byte[240];
            } else {
                date = new byte[(contactses.size() - index) * 40];
            }
            for (int i = index; i < index + 6 && i < contactses.size(); i++) {
                System.arraycopy(contactses.get(i).getbyte(), 0, date, (i - index) * 40, contactses.get(i).getbyte().length);
            }
            CEDevData data = new CEDevData(CEBC.CMD_SEND_TYPE, CEBC.K3.DATA_TYPE_PHONE_BOOK_DOWN);
            data.setData(date);
            byte[] argv = new byte[12];
            argv[0] = (byte) (contactses.size() % 256);
            argv[1] = (byte) (contactses.size() / 256);
            argv[2] = (byte) (index % 256);
            argv[3] = (byte) (index / 256);
            data.setOtherData(argv);
            data.setItemL(Send_contacts.getItemSize());
            data.setItemNumber(date.length / Send_contacts.getItemSize());
            devQueue.push(data);
        }

        /**
         * 获取联系人
         */
        public void getDevContacts() {
            CEDevData data = new CEDevData(CEBC.CMD_REQUEST_TYPE, CEBC.K3.DATA_TYPE_PHONE_BOOK_UP);
            devQueue.push(data);
        }

        /**
         * 发送目标
         */
        public void send_goal(Send_Goal send_goal) {
            devQueue.push(send_goal.toCEDevData());
        }

        /**
         * 发送终止获取联系人
         */
        public void send_not_getContacts() {
            CEDevData data = new CEDevData(CEBC.CMD_SEND_TYPE, CEBC.K3.DATA_TYPE_PHONE_BOOK_TRANSFER_CANCEL);
            devQueue.push(data);
        }

        /**
         * 发送手表首页快捷栏显示控制
         */
        public void send_watch_notifica_workout(Send_Watch_Face_And_Notification_Set_K3 show_k3) {
            devQueue.push(show_k3.toCEDevData());
        }

        /**
         * 发送音乐播放状态
         */
        public void send_music_paly_state(int state) {
            //这个目前不需要使用
//            transDataQueue.putForSend(transData);
            CEDevData data = new CEDevData(CEBC.CMD_SEND_TYPE, CEBC.K3.DATA_TYPE_MUSIC_APP_CMD);
            data.setData(new byte[]{(byte) state});
            data.setItemNumber(1);
            data.setItemL(1);
            devQueue.push(data);
        }

        /**
         * ota升级
         * 请求设备侧的OTA状态
         */
        public void getOTAState() {
            CEDevData data = new CEDevData(CEBC.CMD_REQUEST_TYPE, CEBC.K3.DATA_TYPE_OTA_STATUS);
            devQueue.push(data);
        }

        /**
         * * ota升级
         * 发送OTA数据
         *
         * @param crc        整个文件的CRC item数  和item
         * @param otaFileLen 整个文件的长 包涵文件的头部
         * @param index      这个data 在这个 文件的byte数组中的位置
         * @param data       发送的数据
         */
        public void send_k3_ota_data(int crc, int otaFileLen, int index, byte[] data) {

            CEDevData cedata = new CEDevData(CEBC.CMD_SEND_TYPE, CEBC.K3.DATA_TYPE_OTA_DATA);
            cedata.setData(data);
            cedata.setItemNumber(1);
            cedata.setItemL(data.length);
            byte[] argv = new byte[12];
            System.arraycopy(ByteUtil.int2bytes2(crc), 0, argv, 0, 2);
            System.arraycopy(ByteUtil.intToByte4(otaFileLen), 0, argv, 2, 4);
            System.arraycopy(ByteUtil.intToByte4(index), 0, argv, 6, 4);
            cedata.setOtherData(argv);
            devQueue.push(cedata);
        }

        /**
         * * 发送名片
         */
        public void send_user_card(Send_User_Card send_user_card) {
            devQueue.push(send_user_card.toCEDevData());
        }

        /**
         * 发送日历的提醒数据
         */
        public void send_Note(Send_note send_note) {

            CEDevData cedata = new CEDevData(CEBC.CMD_SEND_TYPE, CEBC.K3.DATA_TYPE_NOTE_REMIND);
            cedata.setData(send_note.getSendbyte());
            cedata.setItemNumber(1);
            cedata.setItemL(send_note.getSendbyte().length);
            devQueue.push(cedata);


        }


    }


    private void handleRcvdBlock(CEDevData data) {
//        Log.e("liu","收到的UserId="+block.getUser_id());
        switch (data.getDataType()) {
            case CEBC.K3.DATA_TYPE_DEVINFO: {
                Handle_K3_Block_Utils_new.handleRcvdBlock_DevInfo(data);
            }
            break;
            case CEBC.K3.DATA_TYPE_BATTERY_INFO:
                Handle_K3_Block_Utils_new.handleRcvdBattery(data);
                break;
            case CEBC.K3.DATA_TYPE_SPORT:
                Handle_K3_Block_Utils_new.handleRcvdSport(data);
                break;
            case CEBC.K3.DATA_TYPE_SLEEP:
//                Handle_K3_Block_Utils_new.handleRcvdSleep(data);
                break;
            case CEBC.K3.DATA_TYPE_DEV_SYNC:
                Handle_K3_Block_Utils_new.handleRcvdMixInfo(data);
                break;
           /* case CEBC.K3.DATA_TYPE_HEART:
                Handle_K3_Block_Utils_new.handleRcvHistoryHeart(data);
                break;
            case CEBC.K3.DATA_TYPE_CURRENT_HEART:
                Handle_K3_Block_Utils_new.handleRcvCurrentHeart(data);
                break;*/
            case CEBC.K3.DATA_TYPE_MIX_SPORT:
                Handle_K3_Block_Utils_new.handleMixSport(data);
                break;
            case CEBC.K3.DATA_TYPE_FIND_PHONE:
                Handle_K3_Block_Utils_new.handleFindPhone(data);
                break;
            case CEBC.K3.DATA_TYPE_PHONE_BOOK_UP://获取联系人
//                Handle_K3_Block_Utils_new.handlegetContacts(data);
                break;
            case CEBC.K3.DATA_TYPE_MUSIC_CONTROL:
//                Handle_K3_Block_Utils_new.handleMusicControl(data);
                break;
            case CEBC.K3.DATA_TYPE_ALARM://接收到设备测的闹钟信息
                Handle_K3_Block_Utils_new.handleGetAlarm(data);
                break;
            case CEBC.K3.DATA_TYPE_OTA_STATUS://获取OTA的升级信息
                Handle_K3_Block_Utils_new.handleOtaInfo(data);
                break;
            case CEBC.K3.DATA_TYPE_PHONE_CONTROL:
                Handle_K3_Block_Utils_new.handlePhoneControl(data);
                break;
            case CEBC.K3.DATA_TYPE_MESSAGE_CONTROL:
                Handle_K3_Block_Utils_new.handleMessageControl(data);
                break;
            case CEBC.K3.DATA_TYPE_USER_CHANGE:
                Log.e("liu", "K3_DATA_TYPE_USER_CHANGE  用户改变");
                Handle_K3_Block_Utils_new.handleUpdateNote(data);
                break;
            default:
                Log.e("liu", "为识别的类型" + data.getDataType() + " --" + data.getData());
                break;
        }
    }


    /**
     * Created by Administrator on 2015/7/3.
     */
    public static class Handle_K3_Block_Utils_new {


        public static Message createMessage(String action, Parcelable parcelable) {
            Message message = Message.obtain();
            Bundle bundle = new Bundle();
            message.what = action.hashCode();
            bundle.putParcelable("data", parcelable);
            message.setData(bundle);
            return message;
        }

        public static Message createMessage(String action, Serializable serializable) {
            Message message = Message.obtain();
            Bundle bundle = new Bundle();
            message.what = action.hashCode();
            bundle.putSerializable("data", serializable);
            message.setData(bundle);
            return message;
        }

        public static Message createMessage(String action, ArrayList<Parcelable> list) {
            Message message = Message.obtain();
            Bundle bundle = new Bundle();
            message.what = action.hashCode();
            bundle.putParcelableArrayList("data", list);
            message.setData(bundle);
            return message;
        }


        /**
         * 处理设备信息
         *
         * @param data
         */
        public static void handleRcvdBlock_DevInfo(CEDevData data) {
            dealDevInfo(data.getData());
        }

        /**
         * 处理电池信息
         *
         * @return
         */
        public static void handleRcvdBattery(CEDevData data) {
            dealRcvdBattery(data.getData());
        }


        public static void handleFindPhone(CEDevData data) {
            byte[] payload = data.getData();
//            getInstance().sendPmessage(createMessage(BC.CMD.ACTION_K3_FIND_PHONE, (int) payload[0]));
        }


        public static void handlePhoneControl(CEDevData data) {
            byte[] payload = data.getData();
            if (payload != null && payload.length > 0) {
//                getInstance().sendPmessage(createMessage(BC.CMD.ACTION_PHONE_CONTROL, new PhoneControl_Struct(payload)));
            }
        }

        /**
         * 短信控制
         */
        public static void handleMessageControl(CEDevData data) {
            byte[] payload = data.getData();
            if (payload != null && payload.length > 0) {
//                getInstance().sendPmessage(createMessage(BC.CMD.ACTION_MESSAGE_CONTROL_CMD, new MessageControl_Struct(payload)));
            }
        }

        /**
         * 需要重新发送所有的日志
         */
        public static void handleUpdateNote(CEDevData data) {
//            getInstance().sendPmessage(createMessage(BC.CMD.ACTION_UPDATE_NOTE,0));
            Log.e("liu", "设备侧发送了，数据重新发送开关");
//            getInstance().sendPmessage(createMessage(BC.CMD.ACTION_UPDATE_NOTE, 0));
        }

        /**
         * 处理闹钟
         */
        public static void handleGetAlarm(CEDevData data) {
            dealGetAlram(data.getData());
        }

        /**
         * 处理混杂信息
         *
         * @return
         */
        public static void handleRcvdMixInfo(CEDevData data) {
            byte[] payload = data.getData();
            if (payload != null && payload.length > 0) {
                Mix_Info_Struct_K3 result = Mix_Info_Struct_K3
                        .parse(payload);
                Log.d("liu", "混杂信息" + result.toString());
                for (Mix_Info_Struct_K3.Property property : result.getList()) {
                    switch (property.getDate_type()) {
                        case CEBC.K3.DATA_TYPE_ALARM://闹钟
                            dealGetAlram(property.getData());
                            Log.e("liu", "闹钟:" + Arrays.toString(property.getData()));
                            break;
                        case CEBC.K3.DATA_TYPE_SETTING://设备设置信息
                            dealGetSetting(property.getData());
                            Log.e("liu", "设备设置信息:" + Arrays.toString(property.getData()));
                            break;
                        case CEBC.K3.DATA_TYPE_DEVINFO://设备信息
                            dealDevInfo(property.getData());
                            Log.e("liu", "设备信息:" + Arrays.toString(property.getData()));
                            break;
                        case CEBC.K3.DATA_TYPE_BATTERY_INFO://电池电量信息
                            dealRcvdBattery(property.getData());
                            Log.d("liu", "电池电量信息:" + Arrays.toString(property.getData()));
                            break;
                        case CEBC.K3.DATA_TYPE_WATCHFACE_MENU_SELECT://16 表盘、通知开关、Workout 设置信息
                            dealWacthFace_Notification_workout(property.getData());
                            Log.e("liu", "表盘设置:" + Arrays.toString(property.getData()));
//                            Log.d("liu", "电池电量信息:" + Arrays.toString(property.getData()));
                            break;
                        case CEBC.K3.DATA_TYPE_OTA_STATUS:
//                         OTA  不需要处理
                            break;
                        case CEBC.K3.DATA_TYPE_NFC_DEV_INFO://  NFC  类型
                            deal_nfc(property.getData());
                            break;
                    }
                }
                //            sendPmessage(BC.CMD.ACTION_OBTAIN_DEVINFO_SUCCESS.hashCode(), dev_Info_Struct);
            }
        }


        /**
         * 处理运动信息
         *
         * @return
         */
        public static void handleRcvdSport(CEDevData data) {
            byte[] payload = data.getData();
            Log.d("luo","payload  = "+payload);
            if (payload != null && payload.length > 0) {
                //            byte[] devInfo = new byte[Sport_Info_Struct_K3.getItemSize()];
                //            System.arraycopy(payload, 0, devInfo, 0,
                //                    Battery_Info_Struct_K3.getItemSize());
                //            Sport_Info_Struct_K3 sport_info_struct_k3 = Sport_Info_Struct_K3
                //                    .parseSportInfo(devInfo);
                //            Log.d("rd65","运动信息"+ sport_info_struct_k3.toString());
                /**
                 * 过滤user_id
                 */
                //            int cur_user_id = getCurUserId();
                //            int rcv_user_id = -1;
                //            try
                //            {
                //                rcv_user_id = Integer.valueOf(block.getUser_id());
                //            }
                //            catch(Exception e)
                //            {
                //                e.printStackTrace();
                //            }
                //            logd("过滤运动数据,cur_user_id:" + cur_user_id + "  rcv_user_id:" + rcv_user_id);
                //
                //            if(cur_user_id==-1)
                //            {
                //                return;
                //            }


                int left_block = data.getItemNumber();
                Log.e("liu", "left_block    运动数据 剩余=" + left_block);
                if (left_block <= 1)
                    left_block = 0;

                Message msg = Message.obtain();
                msg.what = CEBC.K3.ACTION_ANIMATION_FOR_REMAIN_BLOCK.hashCode();
                msg.arg1 = CEBC.TYPE.DATA_REMAIN_SEND_SPORT;
                msg.obj = left_block;
//                    getInstance().sendPmessage(msg);
//                    /**
//                     * 添加同步数据的超时机制
//                     */
//                    getInstance().getSynHandler().removeCallbacks(getInstance().getSysTimeoutRun());
//                    getInstance().getSynHandler().postDelayed(getInstance().getSysTimeoutRun(), 5000);
                int left = payload.length;
                int index = 0;
                while (left > 0) {
                    int this_len = Math.min(left, Sport_Info_Struct_K3.getItemSize());
                    left -= this_len;
                    if (this_len >= Sport_Info_Struct_K3.getItemSize()) {
                        byte[] aSportBytes = new byte[Sport_Info_Struct_K3.getItemSize()];
                        System.arraycopy(payload, index * Sport_Info_Struct_K3.getItemSize(), aSportBytes, 0, Sport_Info_Struct_K3.getItemSize());
                        Sport_Info_Struct_K3 tmpSportInfo = Sport_Info_Struct_K3.parseSportInfo(aSportBytes);
                        //                        if (tmpSportInfo != null && tmpSportInfo.getSteps() <= 1000000)
                        //                        {
                        //                            logd("解析出运动数据: " + tmpSportInfo.toString());
//                            getInstance().sendPmessage(BC.CMD.ACTION_BLUETOOTH_SPORT_DATA.hashCode(), tmpSportInfo);
                        //                        }
                        Log.d("rd65", "运动信息" + tmpSportInfo.toString() + "剩余多少数据包= " + left_block);
                    }
                    index++;
                }
            }
            //            sendPmessage(BC.CMD.ACTION_BLUETOOTH_DATA_CHANGED.hashCode(), null);
            //            sendPmessage(BC.CMD.ACTION_OBTAIN_DEVINFO_SUCCESS.hashCode(), dev_Info_Struct);
        }


        /**
         * 处理混杂运动
         * SPORT_TYPE_NULL = 0;
         * SPORT_TYPE_STOPWATCH = 1;
         * SPORT_TYPE_STEP = 2;
         * SPORT_TYPE_SWIMMING = 3;//游泳
         * SPORT_TYPE_RUN = 4;//跑步
         * SPORT_TYPE_WEIGHT = 5;//举重
         * SPORT_TYPE_HIKE = 6;//徒步
         * SPORT_TYPE_SIT_UP = 7;//仰卧起坐
         * SPORT_TYPE_BENCH = 8;//卧推
         * SPORT_TYPE_SKIPPING = 9;//跳绳
         * SPORT_TYPE_CLIMB = 10;//爬楼梯
         * SPORT_TYPE_SUM = 11;
         */
        public static void handleMixSport(CEDevData data) {
            byte[] payload = data.getData();
            if (payload != null && payload.length > 0) {
                int itemNum = data.getItemNumber();
                int itemSize = data.getItemL();
                Log.d("混杂运动", "itemSize=" + itemSize +"itemNum=" + itemNum +"payload=" + Arrays.toString(payload));
                ByteParser parser = new ByteParser(payload);
                ArrayList<Mix_sport_Struct> list = new ArrayList<>(itemNum);
                try {
                    for (short i = 0; i < itemNum; i++) {
                        list.add(Mix_sport_Struct.parse(parser.readBytes(itemSize)));
                    }
                } catch (Exception e) {
//                    CrashHelper.log(e, "解析混杂运动数据错误", Arrays.toString(payload));
                }
//                getInstance().sendPmessage(createMessage(BC.CMD.ACTION_MIX_SPORT_INFO, list));
            }
        }

        /**
         * 处理获取到的设备信息
         *
         * @param payload
         */
        private static void dealDevInfo(byte[] payload) {
//            if (payload[0] + 1 != payload.length) {
//                Log.e("liu", "设备信息错误，没有按协议" + Arrays.toString(payload));
//                return;
//            }
            byte[] devInfo = new byte[Dev_Info_Struct_K3.devInfoByteLen];
            System.arraycopy(payload, 0, devInfo, 0,
                    Dev_Info_Struct_K3.devInfoByteLen);
            Dev_Info_Struct_K3 dev_Info_Struct = Dev_Info_Struct_K3
                    .parseDevInfo(devInfo);
            Log.d("rd65", "设备信息" + dev_Info_Struct.toString());
//            sendPmessage(createMessage(CEBC.CMD.ACTION_OBTAIN_DEVINFO_SUCCESS, dev_Info_Struct));
        }

        /**
         * 处理电池信息
         *
         * @param payload
         */
        private static void dealRcvdBattery(byte[] payload) {
//            if (payload != null && payload.length == Battery_Info_Struct_K3.getItemSize()) {
            if (payload != null) {
                byte[] devInfo = new byte[Battery_Info_Struct_K3.getItemSize()];
                System.arraycopy(payload, 0, devInfo, 0,
                        Battery_Info_Struct_K3.getItemSize());
                Battery_Info_Struct_K3 dev_Info_Struct = Battery_Info_Struct_K3
                        .parseBatteryInfo(devInfo);
                Log.d("rd65", "电池信息" + dev_Info_Struct.toString());
//                getInstance().sendPmessage(createMessage(BC.CMD.ACTION_INTENT_GET_BATTERY_INFO, dev_Info_Struct));
            }
        }

        /**
         * 处理获取到的闹钟信息
         *
         * @param payload
         */
        private static void dealGetAlram(byte[] payload) {
            int num = payload[0];
            ArrayList<Send_Alarm_Info_Struct_K3> alarm_info_struct_k3s = new ArrayList<>();
            for (int i = 0; i < num; i++) {
                int alarmFirstIndex = i * 4 + 1;
                alarm_info_struct_k3s.add(new Send_Alarm_Info_Struct_K3(payload[alarmFirstIndex],
                        payload[alarmFirstIndex + 1], payload[alarmFirstIndex + 2], payload[alarmFirstIndex + 3]));
            }
//            getInstance().sendPmessage(createMessage(BC.CMD.ACTION_GET_ALARM_CMD, alarm_info_struct_k3s));
        }


        /**
         * 处理设备传过来的设置信息
         *
         * @param payload
         */
        private static void dealGetSetting(byte[] payload) {
//            if (payload != null && payload.length == Send_Dev_Setting_Struct_K3.getItemSize()) {
            if (payload != null) {
                byte[] devInfo = new byte[Send_Dev_Setting_Struct_K3.getItemSize()];
                System.arraycopy(payload, 0, devInfo, 0,
                        Send_Dev_Setting_Struct_K3.getItemSize());
                Send_Dev_Setting_Struct_K3 setting = new Send_Dev_Setting_Struct_K3(devInfo);
                Log.d("rd65", "设备设置信息" + setting.toString());
//                getInstance().sendPmessage(createMessage(BC.CMD.ACTION_GET_SETTING_INFO_CMD, setting));
            }
        }

        /**
         * /16 表盘、通知开关、Workout 设置信息
         *
         * @param payload
         */
        private static void dealWacthFace_Notification_workout(byte[] payload) {
//            if (payload != null && payload.length == Send_Watch_Face_And_Notification_Set_K3.getItemSize()) {
            if (payload != null) {
                byte[] info = new byte[Send_Watch_Face_And_Notification_Set_K3.getItemSize()];
                System.arraycopy(payload, 0, info, 0,
                        Send_Watch_Face_And_Notification_Set_K3.getItemSize());
                Send_Watch_Face_And_Notification_Set_K3 setting = new Send_Watch_Face_And_Notification_Set_K3(info);
//                getInstance().sendPmessage(createMessage(BC.CMD.ACTION_WATCHFACE_NOTIFICATION_WORKOUT_SELECT, setting));
            }

        }


        /**
         * nfc  类型
         *
         * @param payload
         */
        private static void deal_nfc(byte[] payload) {
//            if (payload != null && payload.length == Send_Watch_Face_And_Notification_Set_K3.getItemSize()) {
            if (payload != null) {
                byte[] info = new byte[Dev_NFC_Info.getItemSize()];
                System.arraycopy(payload, 0, info, 0,
                        Dev_NFC_Info.getItemSize());
                Dev_NFC_Info setting = new Dev_NFC_Info(info);
//                getInstance().sendPmessage(createMessage(BC.CMD.ACTION_NFC_TYPE, setting));
            }

        }

        /**
         * 处理ota信息
         */
        public static void handleOtaInfo(CEDevData data) {
            OTAStateInfo otaStateInfo = new OTAStateInfo(data.getData());
//            getInstance().sendPmessage(createMessage(BC.CMD.ACTION_GET_OTA_STATE_INFO, otaStateInfo));
        }

    }
}


